<template>
    <div class="login">
        <!-- 顶部导航 -->
        <van-nav-bar title="圈子登录"></van-nav-bar>

        <!-- 用户名输入框 -->
        <van-field v-model="username" placeholder="用户名"></van-field>

        <!-- 用户密码输入框 -->
        <van-field
            type="password"
            v-model="password"
            placeholder="登录密码"
        ></van-field>

        <!-- 登录按钮 -->
        <van-button type="primary" @click="login">登录</van-button>

        <a @click.prevent="$router.push('/register')">没账号，快速注册</a>
    </div>
</template>

<script>
export default {
    data() {
        return {
            username: "",
            password: ""
        };
    },
    methods: {
        async login() {
            const { username, password } = this;
            const res = await this.$http.post("/login", { username, password });
            if (res.code !== 200) {
                this.$toast({
                    type: "fail",
                    message: res.message
                });
                return;
            }
            // 保存用户登录状态
            window.sessionStorage.setItem("token", res.data.token);
            // 用户信息是对象，所以需要转成字符串（JSON 字符串）
            window.sessionStorage.setItem(
                "user",
                JSON.stringify(res.data.user)
            );
            // 去后端首页
            this.$router.push("/admin/home");
        }
    }
};
</script>

<style lang="less">
.login {
    height: 100vh;
    padding: 0 5px;
    background-color: #eee;

    .van-field,
    .van-button {
        margin-top: 20px;
    }

    .van-button {
        width: 100%;
    }

    a {
        display: inline-block;
        margin-top: 10px;
        color: #666;
        font-size: 14px;
    }
}
</style>
